﻿using Microsoft.Extensions.Logging;
using Model;
using Model.Entities_EF;
using OperationDataBase;
using RSNetDevice;
using RSNetDevice.Data;
using RSNetDevice.Model;
using Service.Mqtt;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Service.Socket
{
    /// <summary>
    /// 回调函数
    /// </summary>
    public partial class Socket_RSServer
    {
        private void RsServer_OnReceiveRealtimeData(RSServer server, RealTimeData data)
        {
            try
            {
                //for (int i = 0; i < 50; i++)
                //{
                _logger.LogWarning($"时间{DateTime.Now}收到{data.NodeList.Count}条");
                //实时数据接收处理
                foreach (NodeData ndata in data.NodeList)//遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
                {
                    var tbhistory = new Tbhistory();
                    tbhistory.Id = string.Join("", Guid.NewGuid().ToString().Split('-'));
                    //DeviceName = "温湿度设备",
                    tbhistory.DeviceAddr = data.DeviceID;
                    tbhistory.NodeId = ndata.NodeID;
                    tbhistory.Hum = ndata.Hum;
                    tbhistory.Tem = ndata.Tem;
                    tbhistory.CoordinateType = Convert.ToByte(ndata.CoordinateType);
                    tbhistory.Lng = data.Lng;
                    tbhistory.Lat = data.Lat;
                    tbhistory.RecordTime = DateTime.Now;
                    //IsAlarmData = Convert.ToByte(true),
                    //Source = Convert.ToByte(true)

                    var result = _dataStorage.TbhistoryToQueue(tbhistory);
                    if (!string.IsNullOrWhiteSpace(result))
                    {
                        _logger.LogInformation(result);
                    }
                }
                //}

            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
            }


            //  _mqttServerService.Publish(data);
        }
        /// <summary>
        /// //设备参数列表接收处理  
        /// </summary>
        /// <param name="server"></param>
        /// <param name="data"></param>
        private void RsServer_OnReceiveParamIds(RSServer server, ParamIdsData data)
        {
            _paramIdsDataHelp.Success = true;
            _paramIdsDataHelp.ParamIdsDataModel = data.PararmIdList;

            //string str = "设备参数编号列表->设备编号：" + data.DeviceID + "\t参数总数量：" + data.TotalCount + "\t本帧参数数量：" + data.Count + "\r\n";
            //foreach (int paramId in data.PararmIdList)//遍历设备中参数id编号
            //{
            //    str += paramId + ",";
            //}
        }
        /// <summary>
        /// //设备参数接收处理
        /// </summary>
        /// <param name="server"></param>
        /// <param name="data"></param>
        private void RsServer_OnReceiveParam(RSServer server, ParamData data)
        {
            if (_receiveParamHelp.ParamDataModel == null)
            {
                _receiveParamHelp.Success = true;
                _receiveParamHelp.ParamDataModel = data;
            }
            else if (_receiveParamHelp.ParamDataModel.ParameterList.Count > 0)
            {
                _receiveParamHelp.ParamDataModel.ParameterList.AddRange(data.ParameterList);
            }
        }
        /// <summary>
        /// 下载设备参数指令应答处理
        /// </summary>
        /// <param name="server"></param>
        /// <param name="data"></param>
        private void RsServer_OnReceiveWriteParamAck(RSServer server, WriteParamAck data)
        {
            _writeParamHelp.Success = true;
            // string str = "下载设备参数->设备编号：" + data.DeviceID + "\t参数数量：" + data.Count + "\t" + (data.Res ? "下载成功" : "下载失败");
            //Invoke(new Action(() =>
            //{
            //    rhtResult.AppendText(str + "\r\n");
            //}));
        }
    }
    /// <summary>
    /// 构造
    /// </summary>
    public partial class Socket_RSServer
    {
        public static ReceiveParamHelp _receiveParamHelp;
        private readonly RSServerSettingsModel _rsServerSettingsModel;
        private readonly Data_Storage _dataStorage;
        private readonly ILogger<Socket_RSServer> _logger;
        private readonly MqttServerService _mqttServerService;

        private readonly WriteParamHelp _writeParamHelp;

        private readonly ParamIdsDataHelp _paramIdsDataHelp;
        private RSServer rsServer;//定义监听服务对象
        public Socket_RSServer(RSServerSettingsModel rsServerSettingsModel,
            Data_Storage dataStorage,
            ILogger<Socket_RSServer> logger,
            MqttServerService mqttServerService,
            WriteParamHelp writeParamHelp,
            ParamIdsDataHelp paramIdsDataHelp
            )
        {
            _rsServerSettingsModel = rsServerSettingsModel;
            _dataStorage = dataStorage;
            _logger = logger;
            _mqttServerService = mqttServerService;
            _writeParamHelp = writeParamHelp;
            _paramIdsDataHelp = paramIdsDataHelp;
        }

        public void Start()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            rsServer = RSServer.Initiate(_rsServerSettingsModel.IP, _rsServerSettingsModel.Port);//初始化
            rsServer.OnReceiveRealtimeData += RsServer_OnReceiveRealtimeData;//实时数据接收处理
            rsServer.OnReceiveParamIds += RsServer_OnReceiveParamIds;//接收设备参数列表处理
            rsServer.OnReceiveParam += RsServer_OnReceiveParam;//接收设备参数处理
            rsServer.OnReceiveWriteParamAck += RsServer_OnReceiveWriteParamAck;//下载参数指令应答处理
            if (!rsServer.Start())
            {
                _logger.LogError($"监听失败 IP:{_rsServerSettingsModel.IP} Port:{_rsServerSettingsModel.Port}");
                return;
            }
            _logger.LogInformation($" 监听成功 \r\n IP:{_rsServerSettingsModel.IP} \r\n Port:{_rsServerSettingsModel.Port}");
        }
    }
    /// <summary>
    /// 召唤指令
    /// </summary>
    public partial class Socket_RSServer
    {
        /// <summary>
        /// 召唤参数编号列表
        /// </summary>
        /// <param name="deviceId"></param>
        public bool ReadParametersList(int deviceId)
        {
            _paramIdsDataHelp.Success = false;
            return rsServer.CallParamList(deviceId);
        }

        /// <summary>
        /// 读取设备参数 
        /// </summary>
        /// <param name="deviceId"></param>
        public async Task<bool> ReadCallParamsAsync(int deviceId, List<int> ids)
        {
            _receiveParamHelp = new ReceiveParamHelp();
            _receiveParamHelp.Success = false;
            return rsServer.CallParam(deviceId, ids);//读取设备参数
        }

        /// <summary>
        /// 下载设备参数  一次性下发参数数量不能超过115个
        /// </summary>
        /// <param name="deviceId"></param>
        public async Task<bool> WriteParametersAsync(int deviceId, int paramid, string paramval)
        {
            List<ParamItem> parameters = new List<ParamItem>();
            try
            {
                parameters.Add(ParamItem.New(paramid, paramval));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return false;
            }
            if (parameters.Count > 115)
            {
                _logger.LogError("一次性下发参数数量不能超过115个");
                return false;
            }
            return rsServer.WriteParam(deviceId, parameters);
        }


    }

}
